LeetCode18, 19,20

LeetCode 第18,19,20题的分析和总结

LeetCode 18. 4Sum

描述:

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路:

3Sum 变形题目,同一个思路

代码:

public List<List<Integer>> fourSum(int[] nums, int target) {
      List<List<Integer>> list = new ArrayList<List<Integer>>();
    List<Integer> l;
    Arrays.sort(nums);
    int len = nums.length;
    for (int i = 0; i < len - 3; i++) {
      // 相同直接返回
      if (i != 0 && nums[i] == nums[i - 1]) continue;
      // 最小值如果大于target,直接的返回
      if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
      // 此值和最大的三个值相加,小于target 直接的返回
      if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 2] < target) continue;

      for (int j = i + 1; j < len - 2; j++) {
        // 相同直接返回
        if (j != i + 1 && nums[j] == nums[j - 1]) continue;
        // 最小值如果大于target,直接的返回
        if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
        // 此值和最大的三个值相加,小于target 直接的返回
        if (nums[i] + nums[j] + nums[len - 1] + nums[len - 2] < target) continue;

        int head = j + 1, end = len - 1;
        while (head < end) {
          int tempt = nums[i] + nums[j] + nums[head] + nums[end];
          if (tempt == target) {
            l = new ArrayList<Integer>();
            l.add(nums[i]);
            l.add(nums[j]);
            l.add(nums[head]);
            l.add(nums[end]);
            list.add(l);
            head++;
			end--;
            while (head < end && nums[head] == nums[head - 1]) {
              head++;
            }
			while (head < end && nums[end] == nums[end+1]) {
              end--;
            }
          } else if (tempt > target)
            end--;
          else
            head++;
        }
      }
    }
    return list; 
}

LeetCode 19. Remove Nth Node From End of List

题目描述:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

思路:

简单题目,注意链表的表头的处理,下标的处理

代码:

public ListNode removeNthFromEnd_copy(ListNode head, int n) {
	ListNode tmp = new ListNode(-1);
	ListNode first = tmp;ListNode second = tmp;
	tmp.next = head;
	for(int i = 1 ; i<=n+1;i++) {
		first = first.next;
	}
	while(first != null) {
		first = first.next;
		second = second.next;
	}
		
	second.next = second.next.next;
		
	return tmp.next;
}

LeetCode 20. Valid Parentheses

题目描述:

Given a string containing just the characters 
'(', ')', '{', '}', '[' and ']', 
determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

思路:

典型的栈的应用,但是有两种不同的思路。

代码:

//正常的思路
public boolean isValid(String s) {
	if(s == null || s.length() <= 0){
   		return true;
   	}
   	Stack<Character> stack = new Stack<Character>();
   	for (int i = 0; i < s.length(); i++) {
   		char cha = s.charAt(i);
		switch (cha) {
		case '(':
		case '{':
		case '[':
			stack.push(cha);
			break;
		case ')':
			if(stack.isEmpty() || stack.pop() != '(' ){
				return false;
			}
			break;
		case '}':
			if(stack.isEmpty() || stack.pop()!= '{' ){
				return false;
			}
			break;
		case ']':
			if(stack.isEmpty() || stack.pop() != '[' ){
			return false;
			}
			break;
		default:
			break;
		}
	}
   	return stack.isEmpty();
}

//匹配的思路

public boolean isValid(String s) {
	Stack<Character> stack = new Stack<Character>();
	for (char c : s.toCharArray()) {
		if (c == '(')
			stack.push(')');
		else if (c == '{')
			stack.push('}');
		else if (c == '[')
			stack.push(']');
		else if (stack.isEmpty() || stack.pop() != c)
			return false;
	}
	return stack.isEmpty();
}

Powered by andiHappy and Theme by AndiHappy